const sharp = require('sharp');
const fs = require('fs');
const path = require('path');

const src = path.join(__dirname, '../public/world.jpg');
const outDir = path.join(__dirname, '../public/earth_tiles');
const tileSize = 1024;
const maxLevel = 5;

if (!fs.existsSync(outDir)) {
  fs.mkdirSync(outDir);
}

function getLevelSize(level) {
  if (level === 1) {
    return { width: 2048, height: 1024, rows: 1, cols: 1 };
  }
  const rows = Math.pow(2, level - 1);
  const cols = Math.pow(2, level);
  return {
    width: cols * tileSize,
    height: rows * tileSize,
    rows,
    cols
  };
}

async function processLevel(level, imageBuffer) {
  if (level > maxLevel) {
    return;
  }
  const { width, height, rows, cols } = getLevelSize(level);
  if (width < tileSize || height < tileSize) {
    return;
  }

  if (level === 1) {
    const outPath = path.join(outDir, '1_0_0.jpg');
    await sharp(imageBuffer, { limitInputPixels: false })
      .resize(width, height)
      .toFile(outPath);
    console.log('第1级完成：1张1024x1024 (1_0_0.jpg)');
    await processLevel(level + 1, imageBuffer);
    return;
  }

  // 其他级别切割成1024x1024小图
  const scaledBuffer = await sharp(imageBuffer, { limitInputPixels: false })
    .resize(width, height)
    .toBuffer();

  let count = 0;
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      const left = col * tileSize;
      const top = row * tileSize;
      const outPath = path.join(outDir, `${level}_${row}_${col}.jpg`);
      await sharp(scaledBuffer, { limitInputPixels: false })
        .extract({ left, top, width: tileSize, height: tileSize })
        .toFile(outPath);
      count++;
    }
  }
  console.log(`第${level}级完成：${count}张1024x1024 (${rows}行${cols}列)`);

  await processLevel(level + 1, imageBuffer);
}

async function main() {
  const imageBuffer = fs.readFileSync(src);
  await processLevel(1, imageBuffer);
}

main(); 